/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

XiaoNuo采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改XiaoNuo源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/xiaonuo-vue
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/xiaonuo-vue
6.若您的项目无法满足以上几点，可申请商业授权，获取XiaoNuo商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.cn.xiaonuo.tcrfinance.fileupload.controller;

import com.cn.xiaonuo.common.entity.BusinessMessage;
import com.cn.xiaonuo.common.utils.StringUtils;
import com.cn.xiaonuo.core.annotion.BusinessLog;
import com.cn.xiaonuo.core.annotion.Permission;
import com.cn.xiaonuo.core.enums.LogAnnotionOpTypeEnum;
import com.cn.xiaonuo.core.pojo.response.ResponseData;
import com.cn.xiaonuo.core.pojo.response.SuccessResponseData;
import com.cn.xiaonuo.tcrfinance.fileupload.param.FileInfoParam;
import com.cn.xiaonuo.tcrfinance.fileupload.service.FileInfoService;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件上传下载控制器
 *
 * @author luyangyang
 * @date 2021-10-27 10:42:51
 */
@CrossOrigin
@RestController
public class FileInfoController {
    private static String[] fileTypes = new String[] { "JPG", "PNG", "GIF" };
    @Resource
    private FileInfoService fileInfoService;

    /**
     * 查询文件上传下载
     *
     * @author luyangyang
     * @date 2021-10-27 10:42:51
     */
    @Permission
    @GetMapping("/api/fileInfo/page")
    @BusinessLog(title = "文件上传下载_查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData page(FileInfoParam fileInfoParam) {
        return new SuccessResponseData(fileInfoService.page(fileInfoParam));
    }

    /**
     * 添加文件上传下载
     *
     * @author luyangyang
     * @date 2021-10-27 10:42:51
     */
    @Permission
    @PostMapping("/api/fileInfo/add")
    @BusinessLog(title = "文件上传下载_增加", opType = LogAnnotionOpTypeEnum.ADD)
    public ResponseData add(@RequestBody @Validated(FileInfoParam.add.class) FileInfoParam fileInfoParam) {
        fileInfoService.add(fileInfoParam);
        return new SuccessResponseData();
    }

    /**
     * 删除文件上传下载
     *
     * @author luyangyang
     * @date 2021-10-27 10:42:51
     */
    @Permission
    @PostMapping("/api/fileInfo/delete")
    @BusinessLog(title = "文件上传下载_删除", opType = LogAnnotionOpTypeEnum.DELETE)
    public ResponseData delete(@RequestBody @Validated(FileInfoParam.delete.class) FileInfoParam fileInfoParam) {
        fileInfoService.delete(fileInfoParam);
        return new SuccessResponseData();
    }

    /**
     * 编辑文件上传下载
     *
     * @author luyangyang
     * @date 2021-10-27 10:42:51
     */
    @Permission
    @PostMapping("/api/fileInfo/edit")
    @BusinessLog(title = "文件上传下载_编辑", opType = LogAnnotionOpTypeEnum.EDIT)
    public ResponseData edit(@RequestBody @Validated(FileInfoParam.edit.class) FileInfoParam fileInfoParam) {
        fileInfoService.edit(fileInfoParam);
        return new SuccessResponseData();
    }

    /**
     * 查看文件上传下载
     *
     * @author luyangyang
     * @date 2021-10-27 10:42:51
     */
    @Permission
    @GetMapping("/api/fileInfo/detail")
    @BusinessLog(title = "文件上传下载_查看", opType = LogAnnotionOpTypeEnum.DETAIL)
    public ResponseData detail(@Validated(FileInfoParam.detail.class) FileInfoParam fileInfoParam) {
        return new SuccessResponseData(fileInfoService.detail(fileInfoParam));
    }

    /**
     * 文件上传下载列表
     *
     * @author luyangyang
     * @date 2021-10-27 10:42:51
     */
    @Permission
    @GetMapping("/api/fileInfo/list")
    @BusinessLog(title = "文件上传下载_列表", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData list(FileInfoParam fileInfoParam) {
        return new SuccessResponseData(fileInfoService.list(fileInfoParam));
    }

    /**
     * 文件上传
     *
     * @param file 文件
     * @return
     */
    @ApiOperation(value = "文件上传", notes = "文件上传")
    @PostMapping("/api/common/fileInfo/uploadFile")
    public BusinessMessage<Map<String, String>> uploadFile(MultipartFile file) {
//        log.debug("文件上传：名称：{}，类型：{}，大小：{}", file.getOriginalFilename(), file.getContentType(), file.getSize());
        BusinessMessage<Map<String, String>> message = new BusinessMessage<>();
        try {
            String url = this.fileInfoService.uploadFile(file);
            message.setCode("200");
            message.setSuccess(!StringUtils.isEmpty(url));
            message.setData(new HashMap<String, String>(1) {{
                put("fileUrl", url);
            }});
        } catch (Exception e) {
            e.printStackTrace();
            message.setCode("-1");
            message.setSuccess(false);
            message.setMessage("操作失败");
//            log.error("文件上传失败，{}", e);
        }
        return message;
    }

    /**
     * 文件上传
     * 如果是图片则会返回宽度和高度
     * 文件路径：imageUrl
     * 图片宽度：width
     * 图片高度：height
     *
     * @param file 文件
     * @return 商品上传结果
     */
    @ApiOperation(value = "文件上传（多返回参数）", notes = "文件上传（多返回参数）")
    @PostMapping("/api/common/fileInfo/uploadImg")
    public BusinessMessage newUpload(MultipartFile file) {
//        log.debug("文件上传：名称：{}，类型：{}，大小：{}", file.getOriginalFilename(), file.getContentType(), file.getSize());
        BusinessMessage message = new BusinessMessage<>();
        try {
            Map<String,Object> data = this.fileInfoService.newUpload(file);
            message.setCode("200");
            message.setSuccess(true);
            message.setData(data);
        } catch (Exception e) {
            e.printStackTrace();
            message.setCode("-1");
            message.setSuccess(false);
            message.setMessage("操作失败");
//            log.error("文件上传失败，{}", e);
        }
        return message;
    }

    /**
     * 文件下载
     *
     * @param name 文件名称
     */
    @ApiOperation(value = "文件下载", notes = "文件下载")
    @PostMapping("/api/common/fileInfo/{name:.*}")
    public ResponseEntity<byte[]> download(@PathVariable String name, Integer width, Integer height) {
//        log.debug("文件下载：名称：{}，宽度：{}，高度：{}", name, width, height);
        return this.fileInfoService.download(name, width, height);
    }

    @ApiOperation(value = "多文件上传", notes = "多文件上传")
    @PostMapping("/api/common/fileInfo/newUpload")
    public BusinessMessage uploadshopimg(List<MultipartFile> files)  {
        BusinessMessage message = new BusinessMessage();
        if(files != null  && files.size() > 0){
            message =  fileInfoService.uploadshopimg(files);
        }else {
            message.setSuccess(false);
            message.setMessage("参数为空");
        }
        return message;
    }

    /**
     * 图片文件上传
     *
     * @param file 文件
     * @return
     */
    @ApiOperation(value = "图片文件上传", notes = "图片文件上传")
    @PostMapping("/api/fileInfo/uploadImg")
    public BusinessMessage<Map<String, String>> uploadImg(MultipartFile file) {
//        log.debug("文件上传：名称：{}，类型：{}，大小：{}", file.getOriginalFilename(), file.getContentType(), file.getSize());
        BusinessMessage<Map<String, String>> message = new BusinessMessage<>();
        try {
            if (file != null && file.getSize() > 0) {
                if (file.getOriginalFilename().getBytes().length > 80) {
                    message.setCode("-1");
                    message.setSuccess(false);
                    message.setMessage("上传文件名称过长!40汉字");
                    return message;
                }
                boolean isContain = this.checkFileType(file.getOriginalFilename()
                        .substring(file.getOriginalFilename().lastIndexOf(".") + 1).toUpperCase());
                if (!isContain) {
                    message.setCode("-1");
                    message.setSuccess(false);
                    message.setMessage("上传文件类型错误!应为JPG或PNG或GIF文件");
                    return message;
                }
            }
            String url = this.fileInfoService.uploadFile(file);
            message.setCode("200");
            message.setSuccess(!StringUtils.isEmpty(url));
            message.setData(new HashMap<String, String>(1) {{
                put("fileUrl", url);
            }});
        } catch (Exception e) {
            e.printStackTrace();
            message.setCode("-1");
            message.setSuccess(false);
            message.setMessage("操作失败");
//            log.error("文件上传失败，{}", e);
        }
        return message;
    }
    /**
     * 检查上传文件类型是否合法
     *
     * @author Sun zhanqiang
     * @time 2012-10-22
     * @param fileType
     * @return
     */
    public static boolean checkFileType(String fileType) {
        for (int i = 0; i < fileTypes.length; i++) {
            if (fileTypes[i].equals(fileType)) {
                return true;
            }
        }
        return false;
    }
}
